﻿using Surpass.Config;
using Surpass.Model.Dto.ResponseDto.ResponseModel.MenuModel;
using Surpass.Model.SysDomain;
using Surpass.Repository.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Surpass.Repository.Repository
{
    public class SysMenuRepository : DataBase,ISysMenuRepository
    {
        private readonly SurpassDbContext _surpassDbContext;
        public SysMenuRepository(SurpassDbContext surpassDbContext):base(surpassDbContext)
        {
            _surpassDbContext = surpassDbContext;
        }

        public dynamic GetSysMenu(long userId)
        {
            //var roleIds = LoadEntities<SysUserRoleRelation>(u => u.UserId == userId).Select(u=>u.RoleId).ToList();
            var query = from menu in _surpassDbContext.SysMenus
                        join menuRole in _surpassDbContext.SysRoleMenuRelations on menu.MenuId equals menuRole.MenuId
                        join userRole in _surpassDbContext.SysUserRoleRelations on menuRole.RoleId equals userRole.RoleId
                        where userRole.UserId==userId && menu.Type== SysConstants.MenuType.Menu
                        select menu ;

            

            return GetMenus(query.Distinct().ToList());


        }

        public List<MenuResponse> GetMenus(List<SysMenu> menus,string ParentMenuId="",int Level = 1)
        {
            return menus.Where(c => c.Level == Level && c.ParentMenuId == ParentMenuId && c.Type == SysConstants.MenuType.Menu).Select(menu => new MenuResponse()
            {
                MenuId = menu.MenuId,
                OrderIndex = menu.OrderIndex,
                Level = menu.Level,
                ParentMenuId = menu.ParentMenuId,
                Icon = menu.Icon,
                MenuName = menu.MenuName,
                Type = menu.Type,
                Url = menu.Url,
                ChildMenus = GetMenus(menus, menu.MenuId, menu.Level+1),
            }).OrderBy(c => c.OrderIndex).ToList();
        }
    }
}
